<?php

namespace App\Models;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Domain\Domain;
use App\Models\Traits\BelongsToApplication;
use Exception;
use GeneaLabs\LaravelModelCaching\Traits\Cachable;
use Illuminate\Database\Eloquent\Relations\HasMany;
use OSS\Core\OssException;
use OSS\Http\RequestCore_Exception;
use OSS\OssClient;

class Aliyun extends Model
{
    use BelongsToApplication,
        Cachable;

    public function objectStorageServices(): HasMany
    {
        return $this->hasMany(ObjectStorageService::class);
    }

    /**
     * 获取当前阿里云账号下的，可用的 oss-bucket
     *
     * @throws RequestCore_Exception
     * @throws OssException
     * @throws Exception
     */
    public function getOssBuckets(): array
    {
        $ossClient = new OssClient($this->app_id, $this->app_secret, 'https://oss.aliyuncs.com');
        $bucketListInfo = $ossClient->listBuckets();
        $buckets = $bucketListInfo->getBucketList();

        $list = [];
        foreach ($buckets as $item) {
            if ($item->getStorageClass() == 'Standard') {
                $list[] = [
                    'id' => $item->getName().'.'.$item->getExtranetEndpoint(),
                    'text' => sprintf(
                        '[%s] %s',
                        $item->getLocation(),
                        $item->getName()
                    ),
                ];
            }
        }

        return $list;
    }

    /**
     * @throws ClientException
     * @throws ServerException
     */
    public function getDomains(): array
    {
        $this->initClient();
        $res = Domain::v20180129()
            ->queryDomainList()
            ->withPageSize(100)
            ->withPageNum(1)
            ->request();
        $list = [];

        foreach ($res->get('Data.Domain') as $item) {
            $list[] = [
                'id' => $item['DomainName'],
                'text' => $item['DomainName'],
            ];
        }

        return $list;
    }

    /**
     * Notes   : 初始化当前的阿里云客户端，可用于域名，DNS等操作
     *
     * @Date   : 2024/8/1 下午2:02
     * @Author : <Jason.C>
     * @throws ClientException
     */
    public function initClient(): void
    {
        AlibabaCloud::accessKeyClient($this->app_id, $this->app_secret)
            ->regionId('cn-hangzhou')
            ->asDefaultClient();
    }
}
